<?php

namespace app\api\model;

use app\common\library\Sms;
use fast\Random;

class Verify
{
    protected static $cacheOptions = [
        // 缓存类型为File
        'type' => 'File',
        // 缓存有效期为永久有效
        'expire' => 900,
        // 指定缓存目录
        'path' => RUNTIME_PATH . 'verify/',
    ];

    //发送验证码
    public function send($mobile,$action)
    {
        $this->mobile = $mobile;
        $res = [
            '_code'=>400,
            'msg'=>'发送失败',
        ];
        if (empty($mobile)) {
            $res['msg'] = ' 手机号不能为空';
        }
        //发送间隔 不到一分钟
        $cacheKey = 'send_' . $mobile;
//        $hasOneMinute = true;
        $hasOneMinute = time() - cache($cacheKey,'') > 60;
        //操作判断
        $user = User::getByMobile($mobile);
        if ($action == 'reg' && $user) {         //注册账号
            $res['msg'] = ' 手机号已注册';
        } elseif ($action != 'reg' && !$user) {  //重置密码
            $res['msg'] = ' 手机号未注册';
        } elseif (!$hasOneMinute) {
            $res['msg'] = ' 60s内不能发送';
        } else {
            $isReg = $action == 'reg' ? true : false;
            $verify = Random::numeric(6);
            cache($cacheKey, time(), 60);
            cache('verify_cache' . $mobile, $verify,self::$cacheOptions);
            $data = [
                'mobile'=>$mobile,
                'isReg'=>$isReg,
                'param'=> $verify,
            ];
            $result = json_decode(Sms::getInstance()->send($data),true);
            if($result['code'] == '000000' && $result['msg'] == 'OK'){
                $res = [
                    '_code'=>200,
                    'msg'=>'发送成功',
                ];
            }
            else{
                $res['_code'] = 500;
            }
        }
        return $res;
    }

    //校验验证码
    public function check($mobile = '', $verify = '')
    {
        $mobile = input('post.mobile',$mobile);
        $verify = input('post.verify',$verify);
        $_verify = cache('verify_cache' . $mobile,'',self::$cacheOptions);
        $check = ($_verify === $verify) && $verify != null ? true : false ;
        if($check){
            cache('verify_cache' . $mobile,null,self::$cacheOptions);
        }
        return $check;
    }
}
